#!/usr/bin/env bash
# Nautilus right-click action: hand the selected files off to the running
# Tailscale GNOME extension via DBus, which shows the native in-shell peer
# picker (same UI as "Send file" in Quick Settings).
#
# Installed by the extension prefs under ~/.local/share/nautilus/scripts/.

set -eu

LOG_TAG="tailscale-taildrop"

notify_ok()   { notify-send -a "Tailscale" -i tailscale-symbolic           "Tailscale" "$1" || true; }
notify_err()  { notify-send -a "Tailscale" -i tailscale-symbolic -u critical "Tailscale" "$1" || true; }
log_err()     { logger -t "$LOG_TAG" -p user.err -- "$1" || true; }

if [ "$#" -eq 0 ]; then
    notify_err "Send with Taildrop: no files selected."
    exit 1
fi

# Build a GVariant "as" array of absolute paths.
ARGS=""
for f in "$@"; do
    abs=$(readlink -f -- "$f")
    esc=${abs//\\/\\\\}
    esc=${esc//\"/\\\"}
    if [ -z "$ARGS" ]; then
        ARGS="\"$esc\""
    else
        ARGS="$ARGS, \"$esc\""
    fi
done

if ! err=$(gdbus call --session \
        --dest org.gnome.Shell \
        --object-path /org/gnome/Shell/Extensions/TailscaleGnome \
        --method org.gnome.Shell.Extensions.TailscaleGnome.SendFiles \
        "[$ARGS]" 2>&1); then
    log_err "DBus SendFiles failed: $err"
    notify_err "Tailscale GNOME extension is not running or DBus call failed."
    exit 1
fi
